<?php

namespace app\http\middleware;

use app\backstage\classes\helper\JwtToken;
use app\backstage\model\ManagerUser;

class VerifyJwt
{
    public function handle($request, \Closure $next)
    {
        $access_token = cookie('access_token');//前后段不分离项目，只能放在cookie里（本来是存到storage里客户端访问带上header头的）
        if (!$access_token) {
            $access_token = $request->header('access_token');
            if (!$access_token) {
                $access_token = $request->param('access_token');
            }
        }
        $isAjax = $request->isAjax();
        if (!$access_token) {
            if ($isAjax) {
                return errJson("请登录完成后访问", 1001);
            }
            return redirect('/manager_user/login');
        }
        $result = JwtToken::parseToken($access_token);
        if (!$result['status']) {
            if ($isAjax) {
                return $result['data'];
            }
            return redirect('/manager_user/login');
        }
        $request->_user = ManagerUser::get($result['uid']);
        if (!$request->_user) {
            return errJson("用户不存在");
        }

        $source_id_second = cookie('source_id_second');
        $source_id_third = cookie('source_id_third');
        $source_id = cookie('source_id');

        if( $source_id == null && $source_id_second == null && $source_id_third == null )
        {
            if($request->_user->status != 1)
            {
                return errJson("账号已禁用");
            }
        }

        $request->_role = $request->_user->role;
        return $next($request);
    }
}
